import json
import re

from django.http import HttpResponse, JsonResponse
from django.views import View
from apps.users.models import User


class UsernameCountView(View):
    def get(self, request, username):
        # 步骤：
        #     1 接受用户名
        print("用户名：%s" % username)
        #     2 根据用户名查数据库
        usercount = User.objects.filter(username=username).count()

        #     3 返回响应
        return JsonResponse({"count": usercount, "code": "0", "errmsg": "OK"})


class MobilesCountView(View):
    def get(self, request, mobiles):
        # 1 接受数据
        print('手机号：%s' % mobiles)

        # 2 验证数据
        # 2.1 验证数据是否存在 有没有传
        if not mobiles:
            return JsonResponse({"code": "400", "errmsg": "mobiles none"})
        # 2.2 正则验证
        if re.match(r'[^1[345789]\d{9}', mobiles):
            return JsonResponse({"code": "400", "errmsg": "mobiles error"})

        # 3 根据手机号查数据库
        mobilecount = User.objects.filter(mobile=mobiles).count()
        print(mobilecount)
        # 4 返回响应（json数据）
        return JsonResponse({'count': mobilecount, "code": "0", "errmsg": "ok"})


class RegisterView(View):
    def post(self, request):
        # 1 接受请求
        body_byte = request.body
        # 获取json格式数据 转为字典
        body_dict = json.loads(body_byte)

        # 2 获取数据
        username = body_dict.get("username")
        password = body_dict.get("password")
        password2 = body_dict.get("password2")
        mobile = body_dict.get("mobile")
        sms_code = body_dict.get("sms_code")
        allow = body_dict.get("allow")

        # 3 验证数据
        # 3.1 验证数据是否为空 有没有传过来
        # all 里传入列表 如果列表里 任一元素为false或为空 结果即使false
        if not all([username, password, password2, mobile, sms_code, allow]):
            print(username)
            print(password)
            print(password2)
            print(mobile)
            print(sms_code)
            print(allow)
            return JsonResponse({"code": "400", "errmsg": "register fail"})
        # 3.2 正则验证
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({"code": "400", "errmsg": "register failz"})

        # 4 生成用户信息保存到数据库
        # user = User(username=username, password=password, mobile=mobile)
        # user.save()

        # 密码加密 数据可能保存不成功捕获异常
        try:
            User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as a:
            print("用户创建失败：%s" % a)

        # 5 返回响应（json数据）
        return JsonResponse({"code": "0", "errmsg": "ok"})


